clear textprogressbar; clear; clc;
%% Create session, Connect devices
PROJ_PATH = [current_file_path(mfilename('fullpath') ) '\'];
session=MeasurementSession.SimpleMeasurement('owner',       'ZN', ...
                                             'name',        'TestSweeper',...
                                             'device_file', [PROJ_PATH 'device.dat'] );
                                         
session.addDescription( ...
    ['This Measurement tests the batch operation of Sweeper Module.' ...
     'Device infomation should be provide in ''device.dat''. '  ...
     'Module settings should be provide in ''settings.mat''. ' ] ...
    );

%% Sweeper Settings
zi = session.getDevice('dev3546');
sweeper = zi.sweepModule(session);
sweeper.load_settings([PROJ_PATH 'settings.mat'], 'swpr_settings');

%% Batch Sweep 
session.addParameter('volt', 0:0.3:0.3, 'V');
session.makeLoopParameter('ScanAux0', 'volt');

result = sweeper.batchRunSession('ScanAux0', @batch_fun);
session.addMeasurementData('ScanAux0', result);

%% Finalize
session.close();
MeasurementSession.save(session);

%% Operations of Each Sweep
function res = batch_fun(session, module, index, varargin)
    %  get Parameters
    p=inputParser;
    isModule = @(x) isa(x, 'EquipmentControl.AnalyseEquipment.ZI.ziModule');
    isSession = @(x) isa(x, 'MeasurementSession.AbstractMeasurementSession');
    
    p.addRequired('session', isSession);
    p.addRequired('module', isModule );
    p.addRequired('index', @isnumeric);
    p.addParameter('processMonitor', @module.plotData);
    p.parse(session, module, index, varargin{:});

    sess = p.Results.session;
    swper = p.Results.module;
    idx = p.Results.index;
    updataPlot = p.Results.processMonitor;
    
    zi = sess.getDevice(swper.device);
    
    fprintf('BatchRun at paramter %s(index = %d): %f ... \n', 'ScanAux0', idx, ...
            sess.getLoopParameter('ScanAux0', idx) );
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %  pre_acquisition operations
    other_operations(sess, zi, idx);
    pause(0.5);
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % data acquisition
    swper.setMonitorNode('auxin0');
    swper.subscribeChannel('0');
    res = swper.run('index', idx, 'silence', 0, 'processMonitor', updataPlot);
    swper.unsubscribeChannel();
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % post_acquisition
    pause(0.5);
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end

function other_operations(sess, zi, idx)
    volt = sess.getLoopParameter('ScanAux0', idx);
    zi.setAuxOutOffset('1', volt );
end